<template>
  <div>
    <breadcrumb-nav menu1="系统管理" menu2="用户列表"></breadcrumb-nav>

    <el-card>
      <!-- 搜索区 -->
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="queryParams.username"
            placeholder="请输入用户名"
            clearable
            @keyup.enter.native="getList"
          />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入姓名"
            clearable
            @keyup.enter.native="getList"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="queryParams.email"
            placeholder="请输入邮箱"
            clearable
            @keyup.enter.native="getList"
          />
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input
            v-model="queryParams.mobile"
            placeholder="请输入手机"
            clearable
            @keyup.enter.native="getList"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="doQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格区 -->
      <el-table :data="userlist" stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="用户名" prop="username"></el-table-column>
        <el-table-column label="姓名" prop="name"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="手机" prop="mobile"></el-table-column>
        <el-table-column label="允许登录" prop="available">
          <template v-slot="scope">
            <el-switch v-model="scope.row.available" @change="userStateChange(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template v-slot="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUser(scope.row.id)"></el-button>
            <el-tooltip content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRoleDialog(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="card-footer">
        <el-button type="primary" @click="showAddDialog">添加用户</el-button>
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.page"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="queryParams.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="50%"
      @close="dialogClosed">
      <el-form :model="form" :rules="rules" ref="form" label-width="70px">
        <el-form-item label="用户名" :prop="editing ? '' : 'username'">
          <el-input v-model="form.username" :disabled="editing"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="form.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="doSave">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    var checkUniqueUsername = (rule, value, callback) => {
      this.$http.get('users/exists/' + value)
        .then(resp => {
          console.log(resp.data.exists)
          if (!resp.data.exists) {
            callback()
          } else {
            callback(new Error('用户名已被占用'))
          }
        })
    }

    return {
      queryParams: { // 搜索表单
        username: '',
        name: '',
        email: '',
        mobile: '',
        page: 1,
        limit: 10
      },
      userlist: [], // table的数据
      total: 0, // 总条数
      dialogVisible: false, // 新增/编辑窗口是否可见
      editing: false, // 编辑or新增
      title: '添加用户', // 新增/编辑窗口的标题
      form: {}, // 新增/编辑表单
      rules: { // 新增/编辑表单的校验规则
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 16, message: '长度在 3 到 16 个字符', trigger: 'blur' },
          { validator: checkUniqueUsername, trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 16, message: '长度在 2 到 16 个字符', trigger: 'blur' }
        ],
        email: [
          { type: 'email', message: '请输入合法的邮箱账号', trigger: 'blur' }
        ],
        mobile: [
          { pattern: /^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/, message: '请输入合法的手机号码', trigger: 'blur' }
        ]
      }
    }
  },

  methods: {
    getList() {
      this.$http.get('users', { params: this.queryParams })
        .then(resp => {
          this.userlist = resp.data.records
          this.total = resp.data.total
        })
    },
    doQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    resetQuery() {
      this.queryParams.username = ''
      this.queryParams.name = ''
      this.queryParams.email = ''
      this.queryParams.mobile = ''
    },
    handleSizeChange(val) {
      this.queryParams.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.queryParams.page = val
      this.getList()
    },
    userStateChange(user) {
      this.$http.put(`users/${user.id}/available/${user.available}`)
        .then(resp => {
          this.$message.success('更新用户状态成功')
        })
        .catch(() => {
          user.available = !user.available // 没有更新成功，恢复状态
        })
    },
    showAddDialog() {
      this.form = {
        username: '',
        name: '',
        email: '',
        mobile: ''
      }
      this.title = '添加用户'
      this.editing = false
      this.dialogVisible = true
    },
    showEditDialog(id) {
      this.$http.get('users/' + id).then(resp => {
        this.form = resp.data
        this.title = '编辑用户'
        this.editing = true
        this.dialogVisible = true
      })
    },
    dialogClosed() {
      this.$refs.form.resetFields()
    },
    doSave() {
      if (this.editing) {
        this.editUser()
      } else {
        this.addUser()
      }
    },
    addUser() {
      this.$refs.form.validate(valid => {
        if (!valid) return
        this.$http.post('users', this.form).then(resp => {
          this.$message.success('添加用户成功！')
          this.dialogVisible = false
          this.getList()
        })
      })
    },
    editUser() {
      this.$refs.form.validate(valid => {
        if (!valid) return
        this.$http.put('users/' + this.form.id, {
          email: this.form.email,
          mobile: this.form.mobile
        }).then(resp => {
          this.$message.success('更新用户信息成功！')
          this.dialogVisible = false
          this.getList()
        })
      })
    },
    removeUser(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete('users/' + id).then(resp => {
          this.$message.success('删除成功!')
          this.getList()
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    }
  },

  created() {
    this.getList()
  }
}
</script>

<style>
</style>
